<template>
  <div>
    <!-- 面包屑导航 -->
    <breadcrumb>
      <span slot="first">首页</span>
      <span slot="second">权限管理</span>
      <span slot="third">角色列表</span>
    </breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="showAddRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限区域 -->
            <el-row :class="['vcenter','bd-bottom',index1 === 0 ? 'bd-top' : '']"
              v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="deleteRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限区域 -->
                <el-row :class="['vcenter',index2 === 0 ? '' : 'bd-top']" v-for="(item2, index2) in item1.children"
                  :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRightsById(scope.row, item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限区域 -->
                  <el-col :span="18">
                    <el-tag closable @close="deleteRightsById(scope.row, item3.id)" type="warning"
                      v-for="(item3, index3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" class="el-icon-edit" @click="editRulesButton(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" class="el-icon-delete" @click="deleteRulesButton(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" class="el-icon-user" @click="setRulesButton(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框区域 -->
    <el-dialog @close="setDiaLogClosed" title="分配权限" :visible.sync="setDialogVisible" width="50%">
      <span>
        <el-tree ref="treeRef" node-key="id" show-checkbox :data="rulesList" :props="setProps" default-expand-all
          :default-checked-keys="checkedList"></el-tree>
      </span>
      <span slot="footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框区域 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <span>
        <el-form :rules="addRoleRules" ref="addRoleRef" :model="addRoleForm" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框区域 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <span>
        <el-form :rules="editRoleRules" ref="editRoleRef" :model="editRoleForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/common/Breadcrumb.vue';
import { request } from '@/network/request'
export default {
  name: "Roles",
  components: {
    Breadcrumb
  },
  data() {
    return {
      // 所有角色列表
      rolesList: [],
      // 所有权限列表
      rulesList: [],
      // 权限列表的层级关系对象
      setProps: {
        label: "authName",
        children: "children"
      },
      // 控制分配权限消息框的显示和隐藏
      setDialogVisible: false,
      // 默认选中节点的数组
      checkedList: [],
      // 当前角色id
      currentId: 0,
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色表单数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则对象
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
      // 控制编辑角色对话框显示隐藏
      editDialogVisible: false,
      // 编辑角色表单验证规则对象
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
      // 编辑角色表单数据对象
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      roleId: 0
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await request({
        url: "roles"
      })
      if (res.meta.status !== 200) return this.$message.error("获取角色列表失败")
      this.rolesList = res.data
    },
    // 指定角色的指定权限删除
    async deleteRightsById(role, rightsId) {
      let flag = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (flag !== "confirm") return
      // console.log(111);
      // 发送网络请求,进行删除
      const { data: res } = await request({
        method: "delete",
        url: `roles/${role.id}/rights/${rightsId}`
      })
      if (res.meta.status !== 200) return this.$message.error("删除失败")
      role.children = res.data
    },
    // 递归函数：把某个角色对应的三级权限添加到默认选中节点的数组中
    recursionSelect(node, arr) {
      // 如果没有children属性，就是三级权限节点
      if (!node.children) return arr.push(node.id)
      node.children.forEach(element => {
        this.recursionSelect(element, arr)
      })
    },
    // 打开分配权限消息框
    async setRulesButton(role) {
      this.currentId = role.id
      // 请求所有权限的数据
      const { data: res } = await request({
        url: "rights/tree"
      })
      if (res.meta.status !== 200) return this.$message.error("请求权限列表失败")
      this.rulesList = res.data
      // 调用递归函数，把角色对应的三级权限添加进权限数组中
      this.recursionSelect(role, this.checkedList)
      // 显示消息框
      this.setDialogVisible = true
    },
    // 当每次对话框被关闭，清空默认选中的数组
    setDiaLogClosed() {
      this.checkedList = []
    },
    // 分配权限确定按钮
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // 发送网络请求，分配权限
      const {data: res} = await request({
        method: "post",
        url: `roles/${this.currentId}/rights`,
        data: {
          rids: idStr
        }
      })
      if (res.meta.status !== 200) return this.$message.error("分配权限失败")
      // 刷新页面
      this.getRolesList()
      this.$message.success("分配权限成功")
      this.setDialogVisible = false
    },
    // 添加角色对话框展示
    showAddRoles() {
      this.addDialogVisible = true
    },
    // 添加角色确定按钮
    addRolesButton() {
      // 进行表单预验证
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return this.$message.error("添加角色失败")
        // 表单预验证成功，发送网络请求
        const {data: res} = await request({
          url: "/roles",
          method: "post",
          data: {
            roleName: this.addRoleForm.roleName,
            roleDesc: this.addRoleForm.roleDesc
          }
        })
        if (res.meta.status !== 201) return this.$message.error("添加角色失败")
        // 刷新页面
        this.getRolesList()
        this.$message.success("添加角色成功")
        this.addDialogVisible = false
      })
    },
    // 编辑角色对话框
    async editRulesButton(role) {
      // console.log(role);
      // 获取原来的角色信息
      this.editRoleForm.roleName = role.roleName
      this.editRoleForm.roleDesc = role.roleDesc
      this.roleId = role.id
      this.editDialogVisible = true
    },
    // 编辑角色对话框确定按钮
    async editRolesButton() {
      // 进行表单预验证
      this.$refs.editRoleRef.validate(valid => {
        if (!valid) return this.$message.warning("请输入角色名称和角色描述")
      })
      // 发送网络请求
      const {data: res} = await request({
        method: "put",
        url: `roles/${this.roleId}`,
        data: {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        }
      })
      if (res.meta.status !== 200) return
      this.$message.success("修改角色信息成功")
      this.getRolesList()
      this.editDialogVisible = false
    },
    // 删除角色
    async deleteRulesButton(role) {
      let flag = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', 
        type: 'warning'
      }).catch(err => err)
      if (flag !== "confirm") return 
      if (flag === "confirm") {
        const {data: res} = await request({
          method: "delete",
          url: `roles/${role.id}`
        })
        if (res.meta.status !== 200) return
        this.$message.success("删除角色成功")
        // 刷新页面
        this.getRolesList()
      }
    }
  },
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 10px;

}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>